<template>
  <div id="app" class="login login-main">
    <!--      <img src="../assets/back.jpg">-->

    <el-row type="flex" justify="center">
      <!-- justify 对齐方式 -->
      <el-col :span="6">
        <el-card shadow="always">
           <div class="block" v-for="fit in fits" :key="fit"><el-avatar :size="80" :src="circleUrl" :fit="fit"></el-avatar></div>
<!--          <h1 style="text-align: center;">欢迎登陆</h1>-->
          <el-divider></el-divider>
          <!-- form表单 -->
          <el-form :model="nameValidateForm" ref="nameValidateForm" label-width="100px" class="demo-ruleForm" @keyup.enter.native="submitForm('nameValidateForm')">
            <!-- 用户名 -->

            <el-form-item
              prop="name"
              :rules="[
                      { required: true, message: '用户名不能为空'},
                      ]"
            >
              <el-input placeholder="请输入用户名" type="text" clearable v-model="nameValidateForm.name" autocomplete="off"
                        prefix-icon="el-icon-user"></el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item
              prop="password"
              :rules="[
                      { required: true, message: '密码不能为空'},
                      ]"
            >
              <el-input placeholder="请输入密码" clearable v-model="nameValidateForm.password" show-password
                        prefix-icon="el-icon-lock"></el-input>
            </el-form-item>
            <el-checkbox v-model="checked" class="remember-me">记住密码</el-checkbox>
            <el-link type="primary" :underline="false" class="forget-password" style="width: 100px">忘记密码？</el-link>
            <!-- 按钮 -->
            <!--                    <el-button type="success" plain>成功按钮</el-button>-->
            <el-button type="success" @click="submitForm('nameValidateForm')" class="login-now">立即登录</el-button>
            <el-button @click="resetForm('nameValidateForm')" class="reset">重置</el-button>
            <el-form-item id="register-box">
              <label class="register">没有账号？
                <el-link type="primary" @click="OpenRegisterFrame=true" class="register-link" :underline="false">去注册
                </el-link>
              </label>
            </el-form-item>

          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="注册账号" :visible.sync="OpenRegisterFrame" class="registerFrame" justify="center">
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
    <el-form-item label="密码" :label-width="formLabelWidth" prop="newPwd" required>
      <el-input  placeholder="请输入密码" clearable v-model="ruleForm.newPwd" type="password" show-password prefix-icon="el-icon-lock" autocomplete="off" class="register-input"></el-input>
    </el-form-item>
    <el-form-item label="确认":label-width="formLabelWidth" prop="confirmPwd" required>
    <el-input placeholder="再次确认密码" clearable v-model="ruleForm.confirmPwd"  show-password prefix-icon="el-icon-lock" type="password" autocomplete="off" class="register-input"></el-input>
    </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="Nack" required>
    <el-input  placeholder="请输入昵称" clearable v-model="ruleForm.Nack" prefix-icon="el-icon-s-custom" autocomplete="off" type="text" class="register-input"></el-input>
    </el-form-item>

        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="Email" required>
    <el-input  placeholder="请输入邮箱" clearable v-model="ruleForm.Email" prefix-icon="el-icon-message" autocomplete="off" type="email" class="register-input"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="OpenRegisterFrame = false" class="cancel-btn">取 消</el-button>
    <el-button type="primary" @click="submitForm('ruleForm')"  class="ok-btn">确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
/*
引入加解密文件
 */
import {SM4EnCrypto,SM4DeCrypto} from "../utils/crypto";

export default {
  data () {
    // 校验
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.confirmPwd !== '') {
          this.$refs.ruleForm.validateField('confirmPwd')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.newPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // ^[\u4e00-\u9fa5]{2,8}$
    var valNickName = (rule, value, callback) => {
      const NameReg = /^[\u4e00-\u9fa5]{2,8}$/
      if (!value) {
        return callback(new Error('昵称不能为空'))
      }
      setTimeout(() => {
        if (NameReg.test(value)) {
          callback()
        } else {
          callback(new Error('昵称格式为 2-8个中文字符'))
        }
      }, 100)
    }
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      fits: ['fill'],
      circleUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      ruleForm: {
        newPwd: '',
        confirmPwd: '',
        Nack: '',
        Email: ''
      },
      rules: {
        newPwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPwd: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur', required: true }
        ],
        Nack: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { validator: valNickName, trigger: 'blur'}
        ],
        Email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur'}
        ]
      },
      nameValidateForm:
        {
          name: '',
          password: ''
        },
      OpenRegisterFrame: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '60px',
      center: true
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (formName === 'ruleForm') {
            // 调取配置文件中的api接口
            this.$ajax.get('../static/config.json').then((res) => {
              this.areaData = res.data // res.data可根据你的数据格式来，看需求
              this.API = this.areaData.api[0].api
              // 向后台请求注册信息
              this.$ajax({
                method: 'post',
                url: this.API + 'CyqRegister',
                data: this.$qs.stringify(this.ruleForm) // 不加stringif可能出现无法接受参数
              }).then((resp) => {
                if (resp.status === 200) {
                  if (resp.data.flag === 0) {
                  // 注册成功，返回消息及账号
                    this.RegisterSuccess(resp.data.ResultMsg, resp.data.account)
                  }
                  // 注册失败
                  else {
                    this.RegisterFail(resp.data.ResultMsg)
                  }
                }
                // 网络错误导致失败
                else {
                  this.RegisterFail(resp.data.ResultMsg)
                }
              })
                .catch((err) => {
                  this.RegisterFail('哎呀，出错啦！')
                })
            })
              .catch((err) => {
                this.RegisterFail('哎呀，配置文件出错啦！')
              })
            // alert("注册成功！")
          } else if (formName === 'nameValidateForm') {
            this.$ajax.get('../static/config.json').then((res) => {
              this.areaData = res.data // res.data可根据你的数据格式来，看需求
              this.API = this.areaData.api[0].api
              // sm4国密加密
              // 向后台请求验证信息
              this.$ajax({
                method: 'post',
                url: this.API + 'login',
                data: this.$qs.stringify({testMsg:SM4EnCrypto(JSON.stringify(this.nameValidateForm))}) // 不加stringif可能出现无法接受参数
              }).then((resp) => {
                if (resp.status === 200) {
                  if (resp.data.flag === 0) {
                    console.log(resp)
                    this.LoginSuccess(resp.data.ResultMsg, resp.data,resp.data.token)
                  } else {
                    this.LoginFail(resp.data.ResultMsg)
                  }
                }
              })
                // eslint-disable-next-line handle-callback-err
                .catch((err) => {
                  this.LoginFail('哎呀，出错啦！')
                })
            })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.LoginFail('哎呀，配置文件出差啦！')
              })
          }
        } else {
          return false
        }
      }
      )
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 注册
    RegisterSuccess (msg, account) { // 注册成功
      this.OpenRegisterFrame = false
      // 注册成功后，先把注册页面关闭后一秒再显示
      setTimeout(() => {
        this.$alert('请记住您的账号：' + account, '注册成功', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'success',
              message: msg
            })
          }
        })
      }, 500)
    },
    RegisterFail (msg) { // 注册失败
      this.$message({
        showClose: true,
        message: msg,
        type: 'error'
      })
    },
    // 登录
    LoginSuccess (msg, res, token) { // 登录成功
      this.$message({
        showClose: true,
        message: msg,
        type: 'success',
        duration: 1000 // 显示1s
      })
      // push需放在sessionStorage之后，不然会出现路由重定向，按两次登录
      window.sessionStorage.setItem('token', token)
      window.sessionStorage.setItem('SetUser', JSON.stringify(res))
      setTimeout(() => {
        this.$router.push({name: 'index', params: {cyq:res}})
        // 登录成功，保存该用户的token
        // 页面跳转刷新，防止停留在缓存中
        //   setTimeout(()=>{
        //登录后刷新页面，加载菜单
        //     window.location.reload();
        //   },2000)
      }, 1000)
    },
    LoginFail (msg) { // 登录失败
      this.$message({
        showClose: true,
        message: msg,
        type: 'error'
      })
    }
  }

}
</script>

<style>
.el-radio-group {
  display: flex;
  /* 边缘 */
  justify-content: center;
}
.el-row--flex {
    display: -webkit-box;
    display: -ms-flexbox;
    /*margin-top: 100px;*/
}
.el-card {
  border-radius: 30px;
  width: 380px;
  margin-top:48%;
  /*margin-left: 50%;*/
  /* box-shadow: 0 2px 12px 0 rgb(243, 102, 102); */
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04); */
}

.grid-content {
  /* background: rgb(14, 214, 131); */
  border-radius: 4px;
  min-height: 50px;
}

/*.el-row {*/
/*  margin-bottom: 20px;*/
/*}*/
.el-input {
  margin-left: -50px;
  width: 280px;
}

.el-form-item {
  width: 300px;
}

</style>
<style>
.remember-me, .forget-password {
  text-align: center;
}

.forget-password, .remember-me {
  width: 50%;
  height: 100%;
  margin: 0 0 20px 20px;
}

.remember-me {
  margin-left: -10px;
}

.forget-password {
  margin-top: 20px;
}

.login-now {
  width: 100px;
  margin: 0 60px 0 -60px;
}
.login-now:hover{
  font-size: 16px;
}
.reset {
  margin: 0 -80px 0 0;
}

/*注册*/
#register-box {
  margin-top: 20px;
  margin-left: 20px;
  margin-bottom: -10px;
}

.register {
  width: 100px;
  margin: 100px -130px 200px 0;
}

.register-link:hover {
  font-size: 18px;
}
/*注册页面*/
.registerFrame{
  width: 50%;
}
.el-dialog{
       display: flex;
       flex-direction: column;
       margin:0 !important;
       position:absolute;
       top:50%;
       left:50%;
       transform:translate(-50%,-50%);
   }

   .el-dialog .el-dialog__body{
       flex:1;
       overflow: auto;
   }
   .register-input{
     margin-left: 10px;
   }
   .cancel-btn{
     margin-left: -100px;
   }
</style>
<style>
/* 背景图片*/
  .login-main{
    background:url(../assets/back2.jpg);
    width: 100%;
    height: 100%;
    position:fixed;
    margin-top: -65px;/*上边距*/
    margin-left: -10px;/*左边距*/
    background-size:100% 100%;
    }
#app{
  margin-top: 0;
}
/*body {*/
/*  height: 723px;*/
/*  background-size: 100% 100%;*/
/*  !*background-repeat: no-repeat;*!*/
/*  background-image: url(../assets/back2.jpg);*/
/*  !*图片不随滚动条滚动*!*/
/*  background-attachment: fixed;*/
/*}*/
</style>
